//
//  Created by inno on 11/12/11.
//
// To change the template use AppCode | Preferences | File Templates.
//


#import "LoginRequest.h"
#import "UrlBuilder.h"
#import "Application.h"
#import "NSString+SBJSON.h"


@implementation LoginRequest

@synthesize url, username, password, listener;

- (NSString *)createTimestamp {
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];
    return [formatter stringFromDate:date];
}

- (NSString *)getUrl {
    UrlBuilder *builder = [UrlBuilder new];
    builder.baseUrl = [self url];
    builder.action = @"login";
    [builder addArgument:@"username" with:[self username]];
    [builder addArgument:@"password" with:[self password]];
    [builder addArgument:@"ts" with:[self createTimestamp]];
    return [builder getUrl];
}

- (void)send {
    NSURL *fullUrl = [NSURL URLWithString:[self getUrl]];
    NSLog(@"sending request %@", fullUrl);
    NSURLRequest *request = [NSURLRequest requestWithURL:fullUrl
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:60.0];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (connection) {
        receivedData = [NSMutableData new];
    } else {
        NSLog(@"connection failed");
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // It can be called multiple times, so each time we reset the data.
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Connection failed! Error - %@ %@",
            [error localizedDescription],
            [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"Succeeded! Received %d bytes of data", [receivedData length]);
    NSString *dataString = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
    NSLog(@"%@", dataString.description);
    NSDictionary *results = [dataString JSONValue];
    [listener onLoginSuccess:[results valueForKey:@"user_type"] :[results valueForKey:@"session"]];
}

@end